package com.kancy.okhttp.client.log.repository;

import com.kancy.okhttp.client.log.HttpRequestLog;
import com.kancy.okhttp.client.log.HttpRequestLogRepository;
import com.kancy.okhttp.client.log.properties.OkHttpClientLogProperties;
import com.mongodb.Mongo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;

import java.util.Map;
import java.util.Objects;

/**
 * HttpRequestLogMongoRepository
 *
 * @author kancy
 * @date 2020/5/2 12:20
 */
@ConditionalOnClass({MongoTemplate.class, Mongo.class})
@ConditionalOnBean({MongoTemplate.class})
@ConditionalOnProperty(prefix = "okhttp.client.log.mongo", name = "enabled", havingValue = "true", matchIfMissing = true)
public class HttpRequestLogMongoRepository implements HttpRequestLogRepository {

    private final OkHttpClientLogProperties properties;
    private final MongoTemplate mongoTemplate;

    public HttpRequestLogMongoRepository(Map<String, MongoTemplate> mongoTemplateMap, OkHttpClientLogProperties properties) {
        this.properties = properties;
        if (mongoTemplateMap.size() == 1){
            mongoTemplate = mongoTemplateMap.values().iterator().next();
        } else {
            mongoTemplate = mongoTemplateMap.get(properties.getMongo().getMongoTemplateBeanName());
        }
    }

    /**
     * 保存第三方日志
     *
     * @param httpRequestLog
     */
    @Async
    @Override
    public void save(HttpRequestLog httpRequestLog) {
        if (Objects.nonNull(mongoTemplate)){
            mongoTemplate.insert(httpRequestLog, properties.getMongo().getCollectionName());
        }
    }
}
